package com.weather.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.weather.vo.WeatherResponse;

/**
 * @Description 天气数据接口实现类
 *
 * @author 堆堆堆
 * @date 2018年5月31日 上午11:07:17
 */
@Service
public class WeatherDataServiceImpl implements WeatherDataService {

	// 天气接口地址
	private static final String WEATHER_URI = "http://wthrcdn.etouch.cn/weather_mini?";

	@Autowired
	private RestTemplate restTemplate;

	@Override
	public WeatherResponse getDataByCityId(String cityId) {

		// 天气接口地址
		String uri = WEATHER_URI + "citykey=" + cityId;
		return this.doGetWeather(uri);
	}

	@Override
	public WeatherResponse getDataByCityName(String cityName) {

		// 天气接口地址
		String uri = WEATHER_URI + "city=" + cityName;
		return this.doGetWeather(uri);
	}

	private WeatherResponse doGetWeather(String uri) {

		ObjectMapper mapper = new ObjectMapper();
		WeatherResponse resp = null;
		String strBody = null;

		// 调用接口
		ResponseEntity<String> respString = restTemplate.getForEntity(uri, String.class);

		// 判断调用结果
		if (respString.getStatusCodeValue() == 200) {
			strBody = respString.getBody();
		}

		// 把 json 转换为实体
		try {
			resp = mapper.readValue(strBody, WeatherResponse.class);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return resp;
	}
}
